package com.roadjava.rbac.bean.dto;

import com.roadjava.rbac.bean.entity.UserDO;
import com.roadjava.rbac.bean.vo.UserRouteVO;
import lombok.Data;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.StringUtils;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;


@Data
public class SecurityUserDTO implements UserDetails {
    /**
     * 用户实体
     */
    private UserDO userDO;

    /**
     * 后端有权限的url列表,如/user/queryById
     * 用于后端判断是否能够授权以及前端的细粒度权限控制
     */
    private Set<String> backAuthorizedUris;

    /**
     * 封装前端的动态路由,前端根据这些动态路由:
     * 1.计算动态路由(vue-router)--tabs
     * 2.计算菜单
     */
    private List<UserRouteVO> userRoutes;

    /**
     * security会调用这个方法来判断当前用户拥有的权限
     */
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        if (CollectionUtils.isEmpty(backAuthorizedUris)) {
            return Collections.emptyList();
        }
        // 转为SimpleGrantedAuthority
        return backAuthorizedUris.stream()
                .filter(StringUtils::hasText)
                .map(SimpleGrantedAuthority::new)
                .collect(Collectors.toList());
    }

    @Override
    public String getPassword() {
        return userDO.getPwd();
    }

    @Override
    public String getUsername() {
        return userDO.getUsername();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}
